<?php

namespace backend\utils;

use Yii;
use yii\helpers\FileHelper;

/**
 * 用法示例：
 *
 * $fileName = '历年实际招生专业'
 * $headArr = ['省名称', '学校名称', '专业名称', '状态']
 * $excel_data = [
 *      ['省名称1', '学校名称1', '专业名称1', '状态1'],
 *      ['省名称2', '学校名称2', '专业名称2', '状态2'],
 *      ['省名称3', '学校名称3', '专业名称3', '状态3'],
 * ]
 *
 * 调用(二选一)：
 * CsvUtil::create_csv_and_down1($fileName, $headArr, $excel_data);
 * CsvUtil::create_csv_and_down2($fileName, $headArr, $excel_data);
 *
 */
class CsvUtil
{
    static function create_csv_and_down1($filename, $titles, $data)
    {
        $fileData = self::create_csv_data($titles, $data);

        self::down2Browser($filename, $fileData);
    }

    static function create_csv_and_down2($filename, $titles, $data)
    {
        $fileData = self::create_csv_data($titles, $data);

        $path = self::create_csv_file($filename, $fileData);

        try {
            AppUtil::download_file($path, $filename);
        } catch (\Exception $e) {
        }

        @unlink(WEB_ROOT . $path);
    }

    /**
     * 字符转换（utf-8 => GBK）
     */
    static function utfToGbk($data)
    {
        return iconv('utf-8', 'GBK', $data);
    }

    /**
     * 生成CSV文件内容
     *
     * Date: 2023/8/28
     */
    static function create_csv_data($titles, $data)
    {
        $line_t = "\n";
        $dou_t = ",";

        // 拼接文件信息，这里注意两点
        // 1、字段与字段之间用逗号分隔开
        // 2、行与行之间需要换行符

        $file_line = "";
        // 表头
        foreach ($titles as $title_t) {
            $file_line .= self::utfToGbk($title_t) . $dou_t;
        }
        $fileData = rtrim($file_line, $dou_t) . $line_t;

        foreach ($data as $value) {
            $file_line = "";
            foreach ($value as $v) {
                $file_line .= $v . $dou_t;
            }
            $fileData .= self::utfToGbk(rtrim($file_line, $dou_t)) . $line_t;
        }

        return $fileData;
    }

    /**
     * 浏览器导出CSV文件格式
     *
     * Date: 2023/8/28
     */
    static function down2Browser($filename, $fileData)
    {
        $filename = self::utfToGbk(rtrim($filename, ".csv") . '.csv');

        header("Content-type:text/csv");
        header('Content-Type: text:application/vnd.ms-excel');
        header("Content-Disposition:attachment;filename=" . $filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Pragma: no-cache');
        header('Expires:0');
        header('Pragma:public');

        echo $fileData;
        exit;
    }

    /**
     * 服务器生成csv文件
     *
     * Date: 2023/8/28
     */
    static function create_csv_file($filename, $fileData)
    {
        $filename = self::utfToGbk(rtrim($filename, ".csv") . '.csv');

        $date = date("Y-m-d");
        $path = '/files/csv/' . $date . '/';
        $filePath = WEB_ROOT . $path;

        if (!is_dir($filePath)) {
            FileHelper::createDirectory($filePath);
        }

        // 将一个字符串写入文件
        file_put_contents($filePath . $filename, $fileData);

        return $path . $filename;
    }

}
